package com.fckbug.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fckbug.Constants;
import com.mysql.jdbc.StringUtils;

/**
 * 头像
 * @author think
 *
 */
public class PhotoServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2389843698411037788L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
		String url = request.getRequestURI();
		int last = url.indexOf("?");
        String userId = url.substring(url.lastIndexOf("/") + 1, last>-1?last:url.length());
        if(StringUtils.isNullOrEmpty(userId)) {
        	userId = Constants.DEFAULT_HEAD;
        }
        OutputStream os = response.getOutputStream();  
        File file = new File(Constants.UPLOAD_PATH+userId+File.separator+"head"+File.separator+"head.jpg");
        if(!file.exists()) {
        	file = new File(Constants.UPLOAD_PATH+Constants.DEFAULT_HEAD+File.separator+"head"+File.separator+"head.jpg");
        }
        FileInputStream fis = new FileInputStream(file);  
        byte[] btImg = readStream(fis);  
        os.write(btImg);  
        os.flush();
        fis.close();
        os.close();
	}
      
    /** 
     * 读取管道中的流数据 
     */  
    public byte[] readStream(InputStream inStream) {  
        ByteArrayOutputStream bops = new ByteArrayOutputStream();  
        int data = -1;  
        try {  
            while((data = inStream.read()) != -1){  
                bops.write(data);  
            }  
            return bops.toByteArray();  
        }catch(Exception e){  
            return null;  
        }  
    }  
}
